package com.ccx.demo.business.code.vo;

import com.alibaba.fastjson.annotation.JSONType;
import com.ccx.demo.business.code.entity.QTabCodeExample;
import com.ccx.demo.business.code.entity.TabCodeExample;
import com.ccx.demo.business.user.entity.QTabUser;
import com.querydsl.jpa.JPAExpressions;
import io.swagger.annotations.ApiModel;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import static com.ccx.demo.business.code.entity.QTabCodeExample.tabCodeExample;


/**
 * <pre>
 * 实体：扩展 {@link TabCodeExample}，增强单个实体的特性，同时满足 join 表的需求
 * 缺点在于 VO 类无法使用全部的 lombok 注解， VO 类继承后必须使用以下 3 个注解
 *
 * *@Getter @Setter @ToString(callSuper = true)
 * *@EqualsAndHashCode(callSuper = true)
 * *@ToString(callSuper = true)
 * </pre>
 *
 * @author 谢长春 2020-01-17
 */
@Getter
@Setter
@ToString(callSuper = true)
@ApiModel(description = "扩展：测试案例表：TabCodeExample")
@JSONType(orders = {"id", "name", "content", "amount", "status", "createTime", "createUserId", "createUserName", "updateTime", "updateUserId", "updateUserName", "deleted", "createUser", "updateUser"})
public class TabCodeExampleJpaExistsVO extends TabCodeExample {

    private static final long serialVersionUID = -7251222373656975725L;

    /**
     * 扩展连表查询字段
     */
    private Long[] createUserIds;
    /**
     * 扩展连表查询字段
     */
    private Boolean hidden;

    @Override
    public QdslWhere where() {
        final QTabCodeExample table = tabCodeExample;
        final QTabUser qTabUser = QTabUser.tabUser;
        // 增强扩展查询条件
        return super.where()
                .and(createUserIds, () -> table.createUserId.in(createUserIds))
/*
SELECT
  tab_code_example.id
, tab_code_example.name
, tab_code_example.createUserId
, tab_code_example.updateUserId
# , tab_user.nickname
FROM tab_code_example
  LEFT JOIN tab_user ON tab_user.id = tab_code_example.createUserId
WHERE tab_code_example.status = 0
  AND tab_user.hidden = 1
#   AND exists(SELECT id from tab_user WHERE id = tab_code_example.createUserId AND hidden = 1)
;
*/
                .and(hidden, () -> JPAExpressions
                        .select(qTabUser.id)
                        .from(qTabUser)
                        .where(qTabUser.id.eq(table.createUserId)
                                .and(qTabUser.hidden.eq(hidden))
                        )
                        .exists()
                );

    }
}
